package com.example.casper.Experiment2024;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.casper.Experiment2024.data.DataBank;
import com.example.casper.Experiment2024.data.RecordShowActivity;
import com.example.casper.Experiment2024.data.Records;
import com.example.casper.Experiment2024.data.RecordsDetailsActivity;
import java.util.ArrayList;
import java.util.List;

public class TravelRecordsFragment extends Fragment {

    public TravelRecordsFragment() {// Required empty public constructor
    }
    private ActivityResultLauncher<Intent> addItemLauncher;
    private ActivityResultLauncher<Intent> updateItemLauncher;
    private ActivityResultLauncher<Intent> showItemLauncher;
    public static List<Records> recordsList = new ArrayList<>();
    private TravelRecordsFragment.RecyclerViewRecordsAdapter adapter;
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 3://"BookDetailsActivity修改成RecordsActivity，完成数据的添加"
                Intent intent = new Intent(this.getContext(), RecordsDetailsActivity.class);
                intent.putExtra("position",item.getOrder()+1);
                addItemLauncher.launch(intent);
                break;
            case 4:
                AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
                builder.setTitle("删除打卡记录");
                builder.setMessage("确定删除这条打卡记录吗?");
                builder.setPositiveButton("确定", (dialog, which) -> {
                    recordsList.remove(item.getOrder());
                    adapter.notifyItemRemoved(item.getOrder());
                    DataBank databank=new DataBank(TravelRecordsFragment.this.getContext());
                    databank.saveRecords(recordsList);
                });
                builder.setNegativeButton("取消", (dialog, which) -> {
                });
                builder.create().show();
                break;
            case 5:
                Intent intentUpdate = new Intent(TravelRecordsFragment.this.getContext(), RecordsDetailsActivity.class);
                Records records= recordsList.get(item.getOrder());
                intentUpdate.putExtra("Title",records.getTitle());
                intentUpdate.putExtra("photo",records.getPhoto());
                intentUpdate.putExtra("description",records.getDescription());
                intentUpdate.putExtra("locationname",records.getLocationname());
                intentUpdate.putExtra("latitude",records.getLatitude());
                intentUpdate.putExtra("longitude",records.getLongitude());
                intentUpdate.putExtra("position",item.getOrder());
                updateItemLauncher.launch(intentUpdate);
                break;
            case 6:
                Intent intentShow=new Intent(TravelRecordsFragment.this.getContext(), RecordShowActivity.class);
                Records recordshow= recordsList.get(item.getOrder());
                intentShow.putExtra("Title",recordshow.getTitle());
                intentShow.putExtra("photo",recordshow.getPhoto());
                intentShow.putExtra("description",recordshow.getDescription());
                intentShow.putExtra("locationname",recordshow.getLocationname());
                intentShow.putExtra("locationname",recordshow.getLocationname());
                intentShow.putExtra("latitude",recordshow.getLatitude());
                intentShow.putExtra("longitude",recordshow.getLongitude());
                intentShow.putExtra("position",item.getOrder());
                showItemLauncher.launch(intentShow);
                break;
            default:
                return super.onContextItemSelected(item);
        }
        return true;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addItemLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        assert data != null;
                        String title = data.getStringExtra("Title"); // 获取返回的数据// 获取返回的数据
                        String text=data.getStringExtra("description");
                        String locatename=data.getStringExtra("locationname");
                        double latitude=data.getDoubleExtra("latitude",113.539333);
                        double longitude=data.getDoubleExtra("longitude",22.242564);
                        ArrayList<String> ImageTour = data.getStringArrayListExtra("photo");
                        int position = data.getIntExtra("position",0);
                        recordsList.add(position,new Records(title, text,latitude,longitude,ImageTour,locatename));
                        adapter.notifyItemInserted(position);
                        DataBank databank=new DataBank(TravelRecordsFragment.this.getContext());
                        databank.saveRecords(recordsList);
                    }
                }
        );
        updateItemLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        assert data != null;
                        int position = data.getIntExtra("position",0);
                        String title = data.getStringExtra("Title"); // 获取返回的数据
                        ArrayList<String> ImageTour = data.getStringArrayListExtra("photo"); // 获取返回的数据
                        String text=data.getStringExtra("description");
                        String locatename=data.getStringExtra("locationname");
                        double latitude=data.getDoubleExtra("latitude",116.397477);
                        double longitude=data.getDoubleExtra("longitude",39.908692);
                        Records records = recordsList.get(position);
                        records.setTitle(title);
                        records.setDescription(text);
                        records.setPhoto(ImageTour);
                        records.setLatitude(latitude);
                        records.setLongitude(longitude);
                        records.setLocationname(locatename);
                        adapter.notifyItemChanged(position);
                        DataBank databank=new DataBank(TravelRecordsFragment.this.getContext());
                        databank.saveRecords(recordsList);
                    }
                }
        );
        showItemLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                }
        );
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootview = inflater.inflate(R.layout.fragment_travel_records, container, false);
        RecyclerView recyclerView = rootview.findViewById(R.id.tour_records_recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        DataBank databank=new DataBank(TravelRecordsFragment.this.getContext());
        recordsList= databank.readRecords();
        if(recordsList.isEmpty())
        {
            ArrayList<String> photo1=new ArrayList<>();
            photo1.add(String.valueOf(R.drawable.jnu1));
            photo1.add(String.valueOf(R.drawable.jnu2));
            photo1.add(String.valueOf(R.drawable.jnu3));
            ArrayList<String> photo2=new ArrayList<>();
            photo2.add(String.valueOf(R.drawable.ymy1));
            photo2.add(String.valueOf(R.drawable.ymy2));
            photo2.add(String.valueOf(R.drawable.ymy3));
            ArrayList<String> photo3=new ArrayList<>();
            photo3.add(String.valueOf(R.drawable.fuhuali1));
            photo3.add(String.valueOf(R.drawable.fuhuali2));
            photo3.add(String.valueOf(R.drawable.fuhuali3));
            ArrayList<String> photo4=new ArrayList<>();
            photo4.add(String.valueOf(R.drawable.bld1));
            photo4.add(String.valueOf(R.drawable.bld2));
            photo4.add(String.valueOf(R.drawable.bld3));
            recordsList.add(new Records("暨南大学","暨南大学（Jinan University）简称“暨大”，本部位于广东省广州市，学校是中央统战部、教育部、广东省人民政府共建的国家“双一流”建设高校，直属中央统战部管理；位列国家“双一流”、“211工程”、 “985工程优势学科创新平台” 、广东省高水平大学重点建设高校。"
                    ,22.25198333333333,113.53601,photo1,"广东省珠海市香洲区前山路206号暨南大学(珠海校区)"));
            recordsList.add(new Records("圆明新园","圆明新园（New Yuanming Palace），位于广东省珠海市香洲区兰埔路与白石路交叉路口西侧。 1992年10月18日，圆明新园奠基，由清华大学建筑学院资深教授设计，以北京圆明园被焚烧前建筑为原稿，根据特定的地理环境、在不破坏原有生态环境的前提下，按1:1比例选建圆明园四十景中的十八景。1997年春节，圆明新园正式对外开放。"
                    ,22.242564,113.539333,photo2,"广东省珠海市香洲区兰埔路与白石路交界处圆明新园"));
            recordsList.add(new Records("富华里","珠海拱北新地标：富华里\n" +
                    "珠海拱北又添新去处！富华里时尚天街，与香港风情相似，给你不一样的体验。\n" +
                    "位于香洲区粤海中路与港一路交汇，周边办公楼、居民区和学校众多，消费人群超65万。\n" +
                    "总建面5万㎡，集酒店、公寓、写字楼、商业于一体，打造地标商业旗舰。"
                    ,22.2345,113.5413,photo3,"广东省珠海市香洲区拱北九洲大道西与白石路交汇处拱北富华里商业街区(象街)"));
            recordsList.add(new Records("白莲洞","白莲洞遗址位于广西壮族自治区柳州市柳石路407号，地处柳州市东南郊白面山南麓，为旧石器时代文化遗址，因洞口有一块白色钟乳石，形似莲花蓓蕾而得名。 \n" +
                    "白莲洞遗址洞口朝南，高5-6米，洞内宽18米，总面积达150多平方米。白莲洞遗址所处的白面山海拔249.8米，高出附近的地平面152米。 遗存文物有人类用火遗迹火坑、人类牙齿化石、石器、陶片，动物化石、动物牙齿化石等。白莲洞遗址提供了探讨华南地区古人类演化及其生产活动，特别是原始农耕与动物驯养活动产生的环境背景。\n" +
                    "1961年，白莲洞遗址被柳州市人民政府公布为市级重点文物保护单位。2006年5月，白莲洞遗址被中华人民共和国国务院公布为为第六批全国重点文物保护单位。\n" +
                    "当前至目的地路线规划"
                    ,22.245,113.5616,photo4,"广东省珠海市香洲区吉大九洲大道中段北侧香洲区白莲洞公园(白莲桥西北)"));
        }
        adapter = new RecyclerViewRecordsAdapter(recordsList, this.getContext());
        recyclerView.setAdapter(adapter);
        registerForContextMenu(recyclerView);
        Button addRecordButton = rootview.findViewById(R.id.add_record_button);
        addRecordButton.setOnClickListener(v -> addRecord());
        return rootview;
    }
    private void addRecord() {
        Intent intent = new Intent(this.getContext(), RecordsDetailsActivity.class);
        intent.putExtra("position",recordsList.size());
        addItemLauncher.launch(intent);
    }
    public static class RecyclerViewRecordsAdapter extends RecyclerView.Adapter<TravelRecordsFragment.RecyclerViewRecordsAdapter.RecordsViewHolder> {
        private final List<Records> recordsList;
        private final Context context;
        public RecyclerViewRecordsAdapter(List<Records> recordsList, Context context) {
            this.recordsList = recordsList;
            this.context = context;
        }
        @NonNull
        @Override
        public TravelRecordsFragment.RecyclerViewRecordsAdapter.RecordsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.records_layout, parent, false);
            return new TravelRecordsFragment.RecyclerViewRecordsAdapter.RecordsViewHolder(view);
        }
        @Override
        public void onBindViewHolder(@NonNull TravelRecordsFragment.RecyclerViewRecordsAdapter.RecordsViewHolder holder, int position) {
            Records records = recordsList.get(position);
            boolean contains = records.getPhoto().get(0).matches("^\\d+$");
            if(contains)
            {
                holder.ImageTour.setImageResource(Integer.parseInt(records.getPhoto().get(0)));
            }
            else holder.ImageTour.setImageURI(Uri.parse(records.getPhoto().get(0)));
            holder.TourTitle.setText(records.getTitle());
            String Brief=records.getDescription() ;
            Brief=Brief.length()>20? Brief.substring(0,20)+"......":Brief;
            holder.TourView.setText(Brief);
            holder.Tourlocation.setText(String.format("%s%s", context.getString(R.string.locate), records.getLocationname()));
            holder.Tourlatitude.setText(String.format("%s%s", context.getString(R.string.latitude), records.getLatitude()));
            holder.Tourlongitude.setText(String.format("%s%s", context.getString(R.string.longitude), records.getLongitude()));
        }
        @Override
        public int getItemCount() {
            return recordsList.size();
        }
        public static class RecordsViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener{
            ImageView ImageTour;
            TextView TourTitle;
            TextView TourView;
            TextView Tourlocation;
            TextView Tourlatitude;
            TextView Tourlongitude;
            public RecordsViewHolder(@NonNull View itemView) {
                super(itemView);
                ImageTour = itemView.findViewById(R.id.image_tour);
                TourTitle = itemView.findViewById(R.id.tourTitle);
                TourView  = itemView.findViewById(R.id.tourViews);
                Tourlocation=itemView.findViewById(R.id.tourLocation);
                Tourlatitude=itemView.findViewById(R.id.tourlatitude);
                Tourlongitude=itemView.findViewById(R.id.tourlongitude);
                itemView.setOnCreateContextMenuListener(this);
            }
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("具体操作");
                menu.add(0, 3, this.getAdapterPosition(), "添加" + this.getAdapterPosition());
                menu.add(0, 4, this.getAdapterPosition(), "删除" + this.getAdapterPosition());
                menu.add(0, 5, this.getAdapterPosition(), "编辑" + this.getAdapterPosition());
                menu.add(0, 6, this.getAdapterPosition(), "查看" + this.getAdapterPosition());
            }//itemId得修改成与BookListFragment中的不一样，否则会导致调用BookListFragment中的onContextItemSelected函数
        }
    }
}

